/// 对话模型类
/// 用于存储和处理用户之间的对话
library;
import 'package:chat_project/models/message_model.dart';
import 'package:chat_project/models/user_model.dart';
import 'package:chat_project/services/storage_service.dart';

class Conversation {
  final String id;
  final User contact;
  final Message? lastMessage;
  final int unreadCount;
  final DateTime updatedAt;

  Conversation({
    required this.id,
    required this.contact,
    this.lastMessage,
    this.unreadCount = 0,
    DateTime? updatedAt,
  }) : updatedAt = updatedAt ?? DateTime.now();

  // 从JSON构造函数
  static Future<Conversation> fromJsonAsync(Map<String, dynamic> json) async {
    // 处理MongoDB返回的_id字段或普通id字段
    final String id = json['_id']?.toString() ?? json['id'] ?? '';
    
    // 处理联系人数据
    User contact;
    if (json['contact'] != null) {
      contact = User.fromJson(json['contact'] as Map<String, dynamic>);
    } else if (json['participants'] != null && json['participants'] is List) {
      // 获取当前用户ID以便找出对方用户
      final storageService = StorageService();
      final currentUser = await storageService.getUser();
      final currentUserId = currentUser?.id ?? '';
      
      // 从participants列表中找出不是当前用户的那个作为联系人
      final List participants = json['participants'];
      if (participants.isNotEmpty) {
        // 尝试查找对方用户（非当前用户）
        dynamic otherParticipant;
        
        // 查找非当前用户的参与者
        for (var participant in participants) {
          final participantId = participant is Map ? 
              participant['_id']?.toString() ?? participant['id']?.toString() : 
              participant.toString();
          
          if (participantId != currentUserId) {
            otherParticipant = participant;
            break;
          }
        }
        
        // 如果找到了非当前用户的参与者
        if (otherParticipant != null) {
          if (otherParticipant is Map) {
            contact = User.fromJson(otherParticipant as Map<String, dynamic>);
          } else {
            // 如果只有ID，则创建一个基本用户对象
            // 这种情况通常是后端没有正确返回用户信息的临时解决方案
            final participantId = otherParticipant.toString();
            final nameLength = participantId.length < 4 ? participantId.length : 4;
            contact = User(
              id: participantId,
              username: '用户${participantId.substring(0, nameLength)}',
              email: '',
            );
          }
        } else {
          // 如果找不到其他用户，使用第一个参与者
          if (participants[0] is Map) {
            contact = User.fromJson(participants[0] as Map<String, dynamic>);
          } else {
            final participantId = participants[0].toString();
            final nameLength = participantId.length < 4 ? participantId.length : 4;
            contact = User(
              id: participantId,
              username: '用户${participantId.substring(0, nameLength)}',
              email: '',
            );
          }
        }
      } else {
        contact = User(id: '', username: '未知用户', email: '');
      }
    } else {
      contact = User(id: '', username: '未知用户', email: '');
    }
    
    return Conversation(
      id: id,
      contact: contact,
      lastMessage: json['lastMessage'] != null 
          ? Message.fromJson(json['lastMessage'] as Map<String, dynamic>) 
          : null,
      unreadCount: json['unreadCount'] ?? 0,
      updatedAt: json['updatedAt'] != null 
          ? DateTime.parse(json['updatedAt']) 
          : DateTime.now(),
    );
  }
  
  // 同步版本，用于兼容性
  factory Conversation.fromJson(Map<String, dynamic> json) {
    // 处理MongoDB返回的_id字段或普通id字段
    final String id = json['_id']?.toString() ?? json['id'] ?? '';
    
    // 处理联系人数据
    User contact;
    if (json['contact'] != null) {
      contact = User.fromJson(json['contact'] as Map<String, dynamic>);
    } else if (json['participants'] != null && json['participants'] is List) {
      // 从participants列表中找出可用的用户作为联系人
      final List participants = json['participants'];
      if (participants.isNotEmpty) {
        // 查找可能包含完整用户信息的参与者
        dynamic userInfo = participants.firstWhere(
          (p) => p is Map && (p['username'] != null || p['email'] != null),
          orElse: () => participants[0]
        );
        
        if (userInfo is Map) {
          contact = User.fromJson(userInfo as Map<String, dynamic>);
        } else {
          // 如果只有ID，则创建一个基本用户对象
          final userIdStr = userInfo.toString();
          final nameLength = userIdStr.length < 4 ? userIdStr.length : 4;
          contact = User(
            id: userIdStr,
            username: '用户${userIdStr.substring(0, nameLength)}',
            email: '',
          );
        }
      } else {
        contact = User(id: '', username: '未知用户', email: '');
      }
    } else {
      contact = User(id: '', username: '未知用户', email: '');
    }
    
    return Conversation(
      id: id,
      contact: contact,
      lastMessage: json['lastMessage'] != null 
          ? Message.fromJson(json['lastMessage'] as Map<String, dynamic>) 
          : null,
      unreadCount: json['unreadCount'] ?? 0,
      updatedAt: json['updatedAt'] != null 
          ? DateTime.parse(json['updatedAt']) 
          : DateTime.now(),
    );
  }

  // 转换为JSON方法
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'contact': contact.toJson(),
      'lastMessage': lastMessage?.toJson(),
      'unreadCount': unreadCount,
      'updatedAt': updatedAt.toIso8601String(),
    };
  }

  // 复制方法，用于更新对话信息
  Conversation copyWith({
    String? id,
    User? contact,
    Message? lastMessage,
    int? unreadCount,
    DateTime? updatedAt,
  }) {
    return Conversation(
      id: id ?? this.id,
      contact: contact ?? this.contact,
      lastMessage: lastMessage ?? this.lastMessage,
      unreadCount: unreadCount ?? this.unreadCount,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }
}